<template>
  <div style="border: 0.0052rem solid #ccc">
    <Toolbar
      style="border-bottom: 0.0052rem solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="min-height: 1.8rem; overflow-y: auto"
      v-model="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
      @onChange="onChange"
      @onDestroyed="onDestroyed"
      @customPaste="customPaste"
    />
  </div>
</template>

<script>
import Vue from "vue"
import { Editor, Toolbar } from "@/plugins/WangEditor"
import { UPLOAD_PATH } from "@/utils/settings"
import store from "@/store"

export default Vue.extend({
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: "",
      toolbarConfig: {
        excludeKeys: ["group-video"]
      },
      editorConfig: {
        placeholder: "请输入内容...",
        autoFocus: true,
        MENU_CONF: {
          uploadImage: {
            base64LimitSize: 5 * 1024,
            fieldName: "file",
            server: UPLOAD_PATH,
            headers: {
              Authorization: "Bearer " + store.getters.token
            },
            customInsert(res, insertFn) {
              insertFn(res.data)
            }
          }
        }
      },
      mode: "default" // or 'simple'
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onChange() {
      this.$emit("changeHTML", this.editor.getHtml())
    },
    onDestroyed(editor) {
      console.log("onDestroyed", editor)
    },
    //粘贴
    customPaste(editor, event, callback) {
      const text = event.clipboardData.getData("text/plain")
      editor.insertText(text)
      event.preventDefault()
      callback(false)
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
})
</script>

<style lang="scss" scoped></style>
